/*
 * @Author: 15801208559 1593215788@qq.com
 * @Date: 2023-12-07 12:52:00
 * @LastEditors: 15801208559 1593215788@qq.com
 * @LastEditTime: 2023-12-07 13:09:39
 * @FilePath: \dm-gpt-survery\dm-chatgpt-web\src\utils\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */


import { UserInfo} from "@/types"
type Token = string | null | undefined

export const USER_INFO = "USER_INFO";
export const TOKEN = "DM_GPT_TOKEN";

function getToken(isLocal: boolean, key: string) {
  return getKey(isLocal, key)
}

function getKey(isLocal: boolean, key: string) {
  return JSON.parse(getStorage(isLocal).getItem(key) || "null");
}


function getStorage(isLocal: boolean) {
  return isLocal ? window.localStorage : window.sessionStorage;
}

function setKey(isLocal: boolean, key: string, data: any) {
  getStorage(isLocal).setItem(key, JSON.stringify(data || null));
}

function getLocalUser() {
  return getKey(true, USER_INFO);
}


function saveUser(info: UserInfo) {
  setKey(true, USER_INFO, info);
  setKey(false, USER_INFO, info);
}


function saveToken(token: Token) {
  setKey(true, TOKEN, token)
}

export {
  getToken,
  getKey,
  setKey,
  saveUser,
  getLocalUser,
  saveToken
};